<template>
  <div class="container">
    <!-- ================================主要表格区================ -->
    <div class="main_table_area">
      <!-- 操作 -->
      <div class="op_btns">
        <el-button type="danger" @click="batchDeleteByIds" class="el-icon-delete" plain size="small"
          v-show="deleteUsersStatus">批量删除选中用户</el-button>
        <el-button type="info" @click="batchDisableByIds" class="el-icon-turn-off" plain size="small"
          v-show="disableUsersStatus">批量禁用选中用户</el-button>
        <el-button type="primary" @click="batchEnableByIds" class="el-icon-open" plain size="small"
          v-show="enableUsersStatus">批量启用选中用户</el-button>
        <el-button type="primary" @click="showAddItemDrawer" class="el-icon-plus" plain size="small">新增用户</el-button>
      </div>
      <!-- 搜索数据 -->
      <div class="search_area">
        <div class="search_item">
          <el-select v-model="mainTable.search.gender" size="small" @change="toSearch" placeholder="用户性别">
            <el-option label="性别不限" :value="null"></el-option>
            <el-option :label="g.label" :value="g.value" v-for="g in select.gendersWithLabel" :key="g.value"></el-option>
          </el-select>
          <el-button size="small" icon="el-icon-refresh" @click="refreshGenders"></el-button>
        </div>
        <div class="search_item">
          <el-select v-model="mainTable.search.enabled" size="small" @change="toSearch" placeholder="用户状态">
            <el-option label="状态不限" :value="null"></el-option>
            <el-option :label="s.label" :value="s.value" v-for="s in select.statusWithLabel" :key="s.value"></el-option>
          </el-select>
          <el-button size="small" icon="el-icon-refresh" @click="refreshStatuses"></el-button>
        </div>
        <div class="search_item">
          <el-input v-model="mainTable.search.name" placeholder="用户名称" clearable size="small"></el-input>
          <el-button type="primary" @click="toSearch" class="el-icon-refresh" plain size="small">刷新表格</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="mainTable.data" border highlight-current-row size="small"
        @selection-change="selectionChangeHandle">
        <template slot="empty">
          <el-empty description="什么用户都没有"></el-empty>
        </template>
        <!-- 复选列 -->
        <el-table-column type="selection" fixed></el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <!-- 展开列 -->
        <el-table-column type="expand" label="详情">
          <template slot-scope="{row}">
            <el-descriptions :title="row.name" :column="1" border size="small">
              <el-descriptions-item :label="col.label" v-for="col in mainTable.expandColumns" :key="col.id">
                <span>{{ row[col.prop] }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <!-- 动态列 -->
        <el-table-column show-overflow-tooltip :min-width="col.minWidth" :label="col.label" :prop="col.prop"
          v-for="(col, index) in mainTable.columns" :key="index">
        </el-table-column>
        <!-- 特殊处理列 -->
        <el-table-column label="性别" width="70px">
          <template slot-scope="{row}">
            <span>{{ row.gender === 0 ? '未设置' : (row.gender === 1 ? '男' : '女') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="70px">
          <template slot-scope="{row}">
            <el-tag type="success" v-if="row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="240px">
          <template slot-scope="{row}">
            <el-button type="primary" @click="showEditItemDrawer(row)" class="el-icon-edit" plain
              size="small">编辑用户</el-button>
            <el-tooltip :content="`给 ${row.name} 分配角色`" placement="left-start">
              <el-button type="primary" @click="showAllocateDrawer(row)" class="el-icon-open" plain
                size="small">分配角色</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="padding:10px; display: flex; justify-content:space-around; ">
        <el-pagination hide-on-single-page layout="total, sizes, prev, pager, next, jumper" next-text="下一页"
          prev-text="上一页" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="mainTable.page.currentPage" :page-size="mainTable.page.pageSize" :total="mainTable.page.total">
        </el-pagination>
      </div>
    </div>
    <!-- ===============================用户分配角色抽屉=============== -->
    <div class="allocate_role_area">
      <el-drawer :withHeader="false" :visible="allocateRoleDrawer.visible" size="100%" direction="btt"
        :before-close="allocateRoleDrawerClose">
        <div class="allocate_caontainer">
          <!-- 已分配区 -->
          <div class="allocate_item">
            <p>{{ allocateRoleDrawer.user ? allocateRoleDrawer.user.name : '' }} 已拥有的角色</p>
            <!-- 按钮 -->
            <div>
              <el-button type="danger" @click="batchUnAllocateRoles" class="el-icon-delete" plain
                size="small">批量移除选中角色</el-button>
              <el-button type="info" @click="batchDisableRolesOfUser" class="el-icon-turn-off" plain
                size="small">批量禁用选中角色</el-button>
              <el-button type="primary" @click="batchEnableRolesOfUser" class="el-icon-open" plain
                size="small">批量启用选中角色</el-button>
              <el-button type="primary" @click="allocateRoleDrawer.visible = false" class="el-icon-back" plain
                size="small">退出</el-button>
            </div>
            <!-- 表格 -->
            <el-table :data="allocateRoleDrawer.allocated.data" size="mini"
              @selection-change="allocatedTableSelectionChangeHandle">
              <template slot="empty">
                <el-empty description="该用户什么角色都未拥有"></el-empty>
              </template>
              <!-- 复选列 -->
              <el-table-column type="selection"></el-table-column>
              <!-- 动态列 -->
              <el-table-column show-overflow-tooltip :min-width="col.minWidth" :label="col.label" :prop="col.prop"
                v-for="col in allocateRoleDrawer.allocated.columns" :key="col.id"></el-table-column>
              <!-- 特殊处理列 -->
              <el-table-column label="角色状态" min-width="40px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.roleStatus === 1">启用</el-tag>
                  <el-tag type="info" v-else-if="row.roleStatus === 0">禁用</el-tag>
                  <el-tag type="info" v-else>未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="用户-角色状态" min-width="60px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.enabled === 1">启用</el-tag>
                  <el-tag type="info" v-else-if="row.enabled === 0">禁用</el-tag>
                  <el-tag type="info" v-else>未知</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 未分配区 -->
          <div class="allocate_item">
            <p>{{ allocateRoleDrawer.user ? allocateRoleDrawer.user.name : '' }} 未拥有的角色</p>
            <!-- 操作 -->
            <div>
              <el-button type="success" @click="batchAllocateRoles" class="el-icon-open" plain
                size="small">批量分配选中角色</el-button>
              <el-button type="primary" @click="allocateRoleDrawer.visible = false" class="el-icon-back" plain
                size="small">退出</el-button>
            </div>
            <!-- 表格 -->
            <el-table :data="allocateRoleDrawer.unAllocated.data" size="mini"
              @selection-change="unAllocatedTableSelectionChangeHandle">
              <template slot="empty">
                <el-empty description="没有任何角色可分配"></el-empty>
              </template>
              <!-- 复选列 -->
              <el-table-column type="selection"></el-table-column>
              <!-- 动态列 -->
              <el-table-column show-overflow-tooltip :min-width="col.minWidth" :label="col.label" :prop="col.prop"
                v-for="col in allocateRoleDrawer.unAllocated.columns" :key="col.id"></el-table-column>
              <!-- 特殊处理列 -->
              <el-table-column label="角色状态" min-width="40px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.roleStatus === 1">启用</el-tag>
                  <el-tag type="info" v-else>禁用</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-drawer>
    </div>
    <!-- ===============================新增用户抽屉=============== -->
    <div>
      <el-drawer :visible="addItemDrawer.visible" size="50%" direction="ltr" :before-close="addItemDrawerClose"
        title="新增用户">
        <div class="add_user_area">
          <div id="add_form">
            <el-form :model="addItemDrawer.data" ref="addUserFormRef" label-width="100px" label-position="left"
              size="small">
              <el-form-item label="用户名" prop="name">
                <el-input placeholder="请输入用户名" v-model="addItemDrawer.data.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" placeholder="请输入密码" v-model="addItemDrawer.data.password" clearable
                  show-password></el-input>
              </el-form-item>
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker v-model="addItemDrawer.data.birthday" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="addItemDrawer.data.gender" size="small">
                  <el-radio-button :label="g.value" v-for="g in select.gendersWithLabel" :key="g.value">{{ g.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="addItemDrawer.data.enabled" size="small">
                  <el-radio-button :label="s.value" v-for="s in select.statusWithLabel" :key="s.value">{{ s.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button @click="addItemDrawer.visible = false">取消</el-button>
                <el-button @click="resetFieldsOfAddItemForm">重置</el-button>
                <el-button type="primary" @click="addItem" v-show="addUserStatus">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-drawer>
    </div>
    <!-- ================================编辑用户抽屉============== -->
    <div>
      <el-drawer :visible="editItemDrawer.visible" size="50%" direction="ltr" :before-close="editItemDrawerClose"
        title="编辑用户">
        <div class="edit_user_area">
          <div id="edit_form">
            <el-form :model="editItemDrawer.data" ref="editUserFormRef" label-width="100px" label-position="left"
              size="small">
              <el-form-item label="用户名" prop="name">
                <el-input placeholder="请输入用户名" v-model="editItemDrawer.data.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" placeholder="请输入密码" v-model="editItemDrawer.data.password" clearable
                  show-password></el-input>
              </el-form-item>
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker v-model="editItemDrawer.data.birthday" type="date" placeholder="选择日期" format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="editItemDrawer.data.gender" size="small">
                  <el-radio-button :label="g.value" v-for="g in select.gendersWithLabel" :key="g.value">{{ g.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="editItemDrawer.data.enabled" size="small">
                  <el-radio-button :label="s.value" v-for="s in select.statusWithLabel" :key="s.value">{{ s.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button @click="editItemDrawer.visible = false">取消</el-button>
                <el-button type="primary" @click="editItem" v-show="editUserStatus">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {

  data() {
    return {
      // 单选数据
      select: {
        // 性别选项
        gendersWithLabel: [],
        // 用户状态选项
        statusWithLabel: [],
      },
      // 主要表格
      mainTable: {
        // 动态列
        columns: [
          {
            prop: 'name',
            label: '用户名',
            minWidth: '30px',
          },
          {
            prop: 'createAt',
            label: '创建时间',
            minWidth: '30px',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
            minWidth: '30px',
          },
        ],
        // 展开列
        expandColumns: [
          {
            prop: 'id',
            label: 'ID',
          },
          {
            prop: 'name',
            label: '用户名',
          },
          {
            prop: 'password',
            label: '密码',
          },
          {
            prop: 'birthday',
            label: '出生日期',
          },
          {
            prop: 'creatorName',
            label: '创建者',
          },
          {
            prop: 'createAt',
            label: '创建时间',
          },
          {
            prop: 'updaterName',
            label: '更新者',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
          },
        ],
        // 表格数据
        data: [],
        // 表格选中数据
        selectedData: [],
        // 分页数据
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 搜索数据
        search: {
          gender: null,
          enabled: null,
          name: '',
        },
        // 下拉选择
        enables: [],
      },
      // 分配角色抽屉
      allocateRoleDrawer: {
        // 抽屉可见性
        visible: false,
        // 分配角色需要操作的用户
        user: { id: -999, name: '不存在的用户' },
        // 已分配
        allocated: {
          // 表格选中数据
          selectedData: [],
          // 表格数据
          data: [],
          // 动态列
          columns: [
            {
              prop: 'id',
              label: 'ID',
              minWidth: '20px',
            },
            {
              prop: 'name',
              label: '角色名',
              minWidth: '60px',
            },
            {
              prop: 'description',
              label: '角色描述',
              minWidth: '80px',
            },
          ]
        },
        // 未分配
        unAllocated: {
          // 表格选中数据
          selectedData: [],
          // 表格数据
          data: [],
          // 动态列
          columns: [
            {
              prop: 'id',
              label: 'ID',
              minWidth: '20px',
            },
            {
              prop: 'name',
              label: '角色名',
              minWidth: '80px',
            },
            {
              prop: 'description',
              label: '角色描述',
              minWidth: '60px',
            },
          ]
        }
      },
      // 新增用户抽屉
      addItemDrawer: {
        visible: false,
        // 绑定数据
        data: {
          name: "",
          password: "",
          birthday: "",
          gender: 0,
          enabled: 0,
        },
      },
      // =编辑用户抽屉
      editItemDrawer: {
        visible: false,
        // 绑定数据
        data: {
          name: "",
          password: "",
          birthday: "",
          gender: 0,
          enabled: 0,
        },
      },
    }
  },

  computed: {
    // 借助mapGetters生成计算属性：uiAuthValidateIsNotNeeded、userAuths
    ...mapGetters('uiAuthModule', ['uiAuthValidateIsNotNeeded', 'userAuths']),
    // 各个操作可用性计算属性
    addUserStatus() {
      const { addUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    allocateRolesToUserStatus() {
      const { allocateRolesToUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    deleteUsersStatus() {
      const { deleteUsers: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    disableRolesOfUserStatus() {
      const { disableRolesOfUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    disableUsersStatus() {
      const { disableUsers: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    editUserStatus() {
      const { editUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    enableRolesOfUserStatus() {
      const { enableRolesOfUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    enableUsersStatus() {
      const { enableUsers: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    genderSelectStatus() {
      const { genderSelect: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getRolesOfUserStatus() {
      const { getRolesOfUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getRolesOutOfUserStatus() {
      const { getRolesOutOfUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    getUsersStatus() {
      const { getUsers: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    removeRolesOfUserStatus() {
      const { removeRolesOfUser: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
    statusSelectStatus() {
      const { statusSelect: { finalStatus } } = this.userAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
  },

  methods: {
    //#region 下拉选项方法开始
    // 刷新性别选项
    async refreshGenders() {
      try {
        const { data: res } = await this.$axios.get(`/admin/user/allGenders`)
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.select.gendersWithLabel = res.data
      } catch (e) {
        this.$message.error(e.msg)
        console.dir(e)
      }
    },
    // 刷新状态选项
    async refreshStatuses() {
      try {
        const { data: res } = await this.$axios.get(`/admin/user/allStatus`)
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.select.statusWithLabel = res.data
      } catch (e) {
        this.$message.error(e.msg)
        console.dir(e)
      }
    },
    //#endregion 下拉选项方法结束

    //#region 主表方法开始
    // 表格复选
    selectionChangeHandle(selection) {
      this.mainTable.selectedData = selection
    },
    // 批量删除
    async batchDeleteByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要删除的用户")
      } else {
        try {
          await this.$confirm(`确定删除 ${ids.length} 个用户吗`)
          const { data: res } = await this.$axios({
            url: '/admin/user/batchDeleteByIds',
            method: 'delete',
            data: ids
          })
          if (res.code === 0) {
            this.$message.error(res.msg)
            return
          }
          let msg = ""
          res.data.forEach(delInfo => {
            msg += `<p>${delInfo.label}: ${delInfo.delCount}</P>`
          })
          this.$notify({
            title: '删除详细',
            duration: 0,
            type: 'success',
            dangerouslyUseHTMLString: true,
            message: msg
          });
          this.mainTable.page.currentPage = 1
          this.pagingGetMainTableData()
        } catch (e) {
          if (e === 'cancel') { return }
          this.$message.error(`删除失败`)
          console.dir(e)
        }
      }
    },
    // 批量启用
    async batchEnableByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要启用的用户")
      } else {
        const { data: res } = await this.$axios({
          url: '/admin/user/batchEnableByIds',
          method: 'put',
          data: ids
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.$message.success(`已启用 ${res.data} 个用户`)
        this.pagingGetMainTableData()
      }
    },
    // 批量禁用
    async batchDisableByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要禁用的用户")
      } else {
        const { data: res } = await this.$axios({
          url: '/admin/user/batchDisableByIds',
          method: 'put',
          data: ids
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.$message.success(`已禁用 ${res.data} 个用户`)
        this.pagingGetMainTableData()
      }
    },
    // 搜索
    toSearch() {
      this.mainTable.page.currentPage = 1
      this.pagingGetMainTableData()
    },
    // 分页获取表格数据
    async pagingGetMainTableData() {
      try {
        const { data: res } = await this.$axios({
          url: `/admin/user/pagingGetWithCondition/${this.mainTable.page.currentPage}/${this.mainTable.page.pageSize}`,
          method: 'post',
          data: this.mainTable.search
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.mainTable.data = res.data.data
        this.mainTable.page.total = res.data.total
      } catch (error) {
        this.$message.error(`获取数据失败`)
        console.dir(error)
      }
    },
    // 分页组件处理
    handleSizeChange(pageSize) {
      this.mainTable.page.pageSize = pageSize
      this.pagingGetMainTableData()
    },
    handleCurrentChange(currentPage) {
      this.mainTable.page.currentPage = currentPage
      this.pagingGetMainTableData()
    },
    //#endregion 主表方法结束

    //#region 用户添加方法开始
    // 表单域重置
    resetFieldsOfAddItemForm() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 显示抽屉
    showAddItemDrawer() {
      this.addItemDrawer.visible = true
    },
    // 隐藏抽屉，并刷新数据
    addItemDrawerClose(done) {
      this.addItemDrawer.visible = false
      this.pagingGetMainTableData()
      done()
    },
    // 添加请求
    async addItem() {
      const { data: res } = await this.$axios({
        url: '/admin/user/addUser',
        method: 'post',
        data: this.addItemDrawer.data,
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.$message.success(`已添加 ${res.data} 个用户`)
    },
    //#endregion 用户添加方法结束

    //#region 用户编辑方法开始
    // 显示抽屉
    showEditItemDrawer(user) {
      this.getEditDataOfUserById(user.id)
      this.editItemDrawer.visible = true
    },
    // 获取编辑用户的信息
    async getEditDataOfUserById(userId) {
      const { data: res } = await this.$axios.get(`/admin/user/${userId}`)
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.editItemDrawer.data = res.data
    },
    // 隐藏抽屉，并刷新数据
    editItemDrawerClose(done) {
      this.editItemDrawer.visible = false
      this.pagingGetMainTableData()
      done()
    },
    // 编辑请求
    async editItem() {
      const { data: res } = await this.$axios({
        url: '/admin/user/edit',
        method: 'put',
        data: this.editItemDrawer.data,
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      } else if (res.data === 0) {
        this.$message.info(`修改失败`)
        return
      }
      this.$message.success(res.msg)
    },
    //#endregion 用户编辑方法结束

    //#region 用户分配角色方法开始    
    // 批量启用用户分到的一批角色
    async batchEnableRolesOfUser() {
      const roleIds = this.allocateRoleDrawer.allocated.selectedData.map(item => item.id)
      if (roleIds.length === 0) {
        this.$message.warning('未选择要启用的角色')
        return
      }
      try {
        const { data: res } = await this.$axios({
          url: `/admin/user/batchEnableRolesOfUser/${this.allocateRoleDrawer.user.id}`,
          method: 'put',
          data: roleIds,
        })
        this.$message.success(`已启用条 ${res.data} 记录`)
        this.getAllocatedRoles()
      } catch (error) {
        console.dir(error)
      }
    },
    // 批量禁用用户分配到的一批角色
    async batchDisableRolesOfUser() {
      const roleIds = this.allocateRoleDrawer.allocated.selectedData.map(item => item.id)
      if (roleIds.length === 0) {
        this.$message.warning('未选择要禁用的角色')
        return
      }
      try {
        const { data: res } = await this.$axios({
          url: `/admin/user/batchDisableRolesOfUser/${this.allocateRoleDrawer.user.id}`,
          method: 'put',
          data: roleIds,
        })
        this.$message.success(`已禁用条 ${res.data} 记录`)
        this.getAllocatedRoles()
      } catch (error) {
        console.dir(error)
      }
    },
    // 已分配表格选中变化处理
    allocatedTableSelectionChangeHandle(selection) {
      this.allocateRoleDrawer.allocated.selectedData = selection
    },
    // 未分配表格选中变化处理
    unAllocatedTableSelectionChangeHandle(selection) {
      this.allocateRoleDrawer.unAllocated.selectedData = selection
    },
    // 批量分配角色
    async batchAllocateRoles() {
      const roleIds = this.allocateRoleDrawer.unAllocated.selectedData.map(item => item.id)
      if (roleIds.length === 0) {
        this.$message.warning('未选择要分配的角色')
        return
      }
      try {
        await this.$axios({
          url: `/admin/user/batchAllocateRoles/${this.allocateRoleDrawer.user.id}`,
          method: 'post',
          data: roleIds,
        })
        this.refreshAllocateData()
      } catch (error) {
        console.dir(error)
      }
    },
    // 批量删除已分配角色
    async batchUnAllocateRoles() {
      const roleIds = this.allocateRoleDrawer.allocated.selectedData.map(item => item.id)
      if (roleIds.length === 0) {
        this.$message.warning('未选择要删除的角色')
        return
      }
      try {
        await this.$axios({
          url: `/admin/user/batchUnAllocateRoles/${this.allocateRoleDrawer.user.id}`,
          method: 'post',
          data: roleIds,
        })
        this.refreshAllocateData()
      } catch (error) {
        console.dir(error)
      }
    },
    // 显示抽屉，并初始化数据
    showAllocateDrawer(user) {
      this.allocateRoleDrawer.user = user
      this.refreshAllocateData()
      this.allocateRoleDrawer.visible = true
    },
    // 隐藏抽屉
    allocateRoleDrawerClose(done) {
      this.allocateRoleDrawer.visible = false
      done()
    },
    // 刷新分配信息
    refreshAllocateData() {
      this.getAllocatedRoles()
      this.getUnAllocatedRoles()
    },
    // 获取已分配
    async getAllocatedRoles() {
      try {
        const { data: res } = await this.$axios.get(`/admin/user/allocatedRoles/${this.allocateRoleDrawer.user.id}`)
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.allocateRoleDrawer.allocated.data = res.data
      } catch (error) {
        console.dir(error)
      }
    },
    // 获取未分配
    async getUnAllocatedRoles() {
      const { data: res } = await this.$axios.get(`/admin/user/unAllocatedRoles/${this.allocateRoleDrawer.user.id}`)
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.allocateRoleDrawer.unAllocated.data = res.data
    },
    //#endregion 用户分配角色方法结束
  },

  mounted() {
    // 如果具有获取用户列表权限
    if (this.getUsersStatus) {
      this.pagingGetMainTableData()
    }
    // 如果具有获取性别选项权限
    if (this.genderSelectStatus) {
      this.refreshGenders()
    }
    // 如果具有获取用户状态选项权限
    if (this.statusSelectStatus) {
      this.refreshStatuses()
    }
  }
}
</script>

<style lang="less" scoped>
.main_table_area {
  .op_btns {
    display: flex;
    justify-content: start;
    padding-bottom: 10px;
  }

  .search_area {
    display: flex;
    justify-content: start;
    padding-bottom: 10px;

    .search_item {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-right: 20px;

      .el-select {
        max-width: 150px;
      }

      .el-input {
        max-width: 200px;
        padding-right: 5px;
      }
    }
  }
}

.allocate_role_area {
  .allocate_caontainer {
    height: 100vh;
    display: flex;
    justify-content: space-around;

    .allocate_item {
      height: 100%;
      min-width: 650px;
      padding: 0 0 0 10px;
      margin: 0 10px 0 10px;
      box-shadow: 0px -3px 5px #000;
    }
  }
}

.add_user_area {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;

  #add_form {
    width: 321px;
    padding: 50px;
    border-radius: 10px;
    box-shadow: 0 0 3px #000;
  }
}

.edit_user_area {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;

  #edit_form {
    width: 321px;
    padding: 50px;
    border-radius: 10px;
    box-shadow: 0 0 3px #000;
  }
}
</style>